/**
 * 路由初始化
 * @module router/index
 */
import Vue from 'vue'
import Router from 'vue-router'
import routes from './routes'
import {ssoReq} from '@/base/api/m-search'
import {SSO_PATH} from '@/config'
// import cookie from '@/helper/cookie'
import {save, get} from '@/utils/storage'
const router = new Router(routes)

 // 测试写入cookie
const testAuth = [
    {'qxdm': '1', 'qxmc': '权限1'},
    {'qxdm': '2', 'qxmc': '权限2'},
    {'qxdm': '3', 'qxmc': '权限3'}
]
 save('auth', testAuth)
const ossRequest = function(to, from, next, sfzh) {
    ssoReq({sfzh: sfzh}).then(res => {
        if(res.list) {
         save('auth', res.list, localStorage);
         next()
        } else {
            next(false)
            window.location.href = SSO_PATH
        }
    }).catch(e => {
        next(false)
        window.location.href = SSO_PATH
    })
}

router.beforeEach((to, from, next) => {
    let sfzh = to.query.sfzh;
    if(sfzh) {
      ossRequest(to, from, next, sfzh)
    } else if(get('auth')) {
      ossRequest(to, from, next, get('auth'))
    } else {
        next(false)
        window.location.href = SSO_PATH
    }
})

Vue.use(Router)

export default router
